#
# peerscape.daemon.monitor
#
# Copyright 2008 Helsinki Institute for Information Technology
# and the authors.
#
# Authors: Ken Rimey <rimey@hiit.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

from __future__ import with_statement

import sys
import time
import curses
import locale
from StringIO import StringIO

from peerscape import DB
from peerscape.sync import list_sync_sessions

class Monitor(object):
    def __init__(self, path, daemon=None):
        self.path = path
        self.daemon = daemon    # not used anymore
        self.counter = 0

    def loop(self, interval=0.2):
        self.db = DB(self.path, create=False)
        screen = curses.initscr()
        screen.scrollok(True)
        try:
            while True:
                time.sleep(interval)
                screen.erase()
                screen.addstr(self.get_text())
                screen.refresh()
        finally:
            curses.endwin()
            self.db.close()

    def get_text(self):
        output = StringIO()
        output, sys.stdout = sys.stdout, output
        try:
            self.report()
            return sys.stdout.getvalue()
        finally:
            output, sys.stdout = sys.stdout, output
            output.close()

    def report(self):
        self.counter += 1
        spinner = '|/-\\'[self.counter % 4]
        print 'Peerscape Daemon %s' % spinner
        with self.db.read_transaction():
            #self.report_datasets()
            self.report_sync_sessions()

    def report_datasets(self):
        print '\nDatasets:'
        for iid in self.db.list_datasets():
            info = self.db.get_dataset_info(iid)

            title = self.db.get_text(iid, '/info/title.txt') or iid
            type = info.get('type')
            if type is None:
                notes = ['no data']
            else:
                size_note = '%d bytes' % info['size']
                notes = [type, size_note]

            self.write(title, notes, indent=1)

    def report_sync_sessions(self):
        print '\nSync Sessions:'
        for session in list_sync_sessions(verbose=True):
            self.write(session.get_status_line(), indent=1)
            #self.report_session_datasets(session)

    def report_session_datasets(self, session):
        requested = set(session.datasets_requested)
        served = set(session.datasets_served)
        for iid in self.db.list_datasets():
            if iid in requested | served:
                title = self.db.get_text(iid, '/info/title.txt') or iid
                self.write(title, indent=2)

    def write(self, text, notes=[], indent=0):
        whitespace = '  ' * indent
        if notes:
            text = '%s%s (%s)' % (whitespace, text, ', '.join(notes))
        else:
            text = '%s%s' % (whitespace, text)

        code = locale.getpreferredencoding() or 'us-ascii'
        print text.encode(code, 'replace')
